# -*- coding: utf-8 -*-

# 绘制所有区的生长期NDVI平均值和全年NDVI平均值，每幅图包括所有区的数据

import os
import json
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import make_interp_spline
from matplotlib import font_manager  # 导入字体管理模块

my_font = font_manager.FontProperties(fname="C:/WINDOWS/Fonts/STSONG.TTF")
root_path = "E:\\毕设数据"
x_tick = ['2000', '2001', '2002', '2003', '2004', '2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012',
          '2013', '2014', '2015', '2016', '2017', '2018', '2019', '2020']
plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号

label_font = {'family': 'serif',
        'color': 'black',
        'weight': 'normal',
        'size': 16,
        }

legend_font = {'family': "STSONG",
              # 'color': 'black',
              'weight': 'normal',
              'size': 15,
              }

with open("avgRecord.json") as f:
    data = json.load(f)
    d1 = data['QuNDVI_Excel']


def calc_new_xy(old_x,old_y) -> tuple:
    xx = [x for x in range(0, len(old_x), 1)]
    xn = np.array(xx)
    x_smooth = np.linspace(xn.min(initial=None), xn.max(initial=None), 300)
    y_smooth = make_interp_spline(xn, old_y)(x_smooth)
    return x_smooth, y_smooth


def data_keys_I():
    """数据一级键， 分类标准"""
    dirs = os.listdir(root_path)
    keys_I = []
    for i in dirs:
        if i.endswith("Excel"):
            keys_I.append(i)
    return keys_I


def data_keys_II(key_I):
    """数据二级键，分类标准下的各类别"""
    path_I = os.path.join(root_path, key_I)
    key_II = os.listdir(path_I)
    return key_II

def get_data(key) -> (dict, int):
    key1 = data_keys_I()
    if key in key1 and key != "WuhanNDVI_Excel":
        return data[key], 1
    else:
        if key == "WuhanNDVI_Excel":
            return data[key], 2
        for i in key1:
            key2 = data_keys_II(i)
            if key in key2:
                return data[i][key], 2
        return "not such data"

def draw(keys, types: "growth_avg or year_avg"):
    x = x_tick
    for i in keys:
        print(i)
        data = get_data(i)[0]
        print(data)
        data_flag = get_data(i)[1]
        if data_flag == 2:
            y = data.get(types)
            # y_year = data.get("year_avg")
            new = calc_new_xy(x, y)
            new_x = new[0]
            new_y = new[1]
            if types == "growth_avg":
                title = "生长期（4-10月）变化趋势"
            else:
                title = "年平均变化趋势"
            label = i
            plt.plot(new_x, new_y, label=label)
            plt.title(title, fontproperties=my_font, fontsize=20, pad=20)
            plt.xlabel("Year", fontdict=label_font)
            plt.ylabel("NDVI", fontdict=label_font)

            my_y_ticks = np.arange(0, max(y)+0.1, 0.05)
            plt.xticks(np.arange(0, len(x_tick), 1), x_tick, fontproperties='Times New Roman', size=14)
            plt.yticks(my_y_ticks, fontproperties='Times New Roman', size=14)

        else:
            print("key error")
            return



if __name__ == '__main__':
    key1s = data_keys_I()
    key1 = key1s[1]
    key2s = data_keys_II(key1)
    plt.figure(figsize=(60, 60))
    draw(key2s, "growth_avg")
    # plt.legend(loc=6, prop=legend_font, bbox_to_anchor=(0, 0), borderaxespad=0)
    plt.legend(loc=4, prop=legend_font, bbox_to_anchor=(1.2, 0))
    plt.grid(alpha=0.3, color='g', which="major")

    plt.show()